<template>
  <view class="container">
    <view class="header">
      <image :src="user?.avatarUrlWbxqy" @click="chooseImage" class="avatar"/>
      <text class="user-id">ID: {{ user?.userIdWbxqy?.toString().padStart(8, '0') }}</text>
      <text class="department-name">{{ user?.department?.departmentNameWbxqy }}:{{ user?.usernameWbxqy }}</text>
    </view>
    <view class="form">
      <view class="form-item">
        <text class="label">用户名:</text>
        <input v-model="user.usernameWbxqy" class="input" placeholder="请输入用户名" disabled/>
      </view>
      <view class="form-item">
        <text class="label">邮箱:</text>
        <input v-model="user.emailWbxqy" class="input" placeholder="请输入邮箱"/>
      </view>
      <view class="form-item">
        <text class="label">电话号码:</text>
        <input v-model="user.phoneNumberWbxqy" class="input" placeholder="请输入电话号码"/>
      </view>
      <button class="save-btn" @click="updateUserInfo">保存</button>
    </view>
  </view>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {getUserInfo, updateUser} from '../../api/userMG'

// User object
const user = ref({
  avatarUrlWbxqy: '',
  department: {},
  departmentIdWbxqy: 0,
  emailWbxqy: '',
  passwordWbxqy: '',
  phoneNumberWbxqy: '',
  roleWbxqy: '',
  userIdWbxqy: 0,
  usernameWbxqy: ''
})

// Fetch user info
const fetchUserInfo = async () => {
  try {
    user.value = await getUserInfo()
    console.log(user.value)
  } catch (error) {
    console.error('获取用户信息失败', error)
  }
}

// Page initialization
onMounted(() => {
  fetchUserInfo()
})

// Choose image and upload to server
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const filePath = res.tempFilePaths[0]

      // Upload file to server
      uni.uploadFile({
        url: 'http://localhost:9999/upload', // Your backend file upload URL
        filePath: filePath,
        name: 'file', // Name of the file form field
        success: (uploadFileRes) => {
          const data = JSON.parse(uploadFileRes.data) // Assuming the backend returns JSON
          if (data.url) {
            user.value.avatarUrlWbxqy = data.url // Update user's avatar with the uploaded URL
            console.log('Upload success, file URL:', data.url)
          }
        },
        fail: (err) => {
          console.error('上传文件失败', err)
        }
      })
    }
  })
}

// Update user info
const updateUserInfo = async () => {
  try {
    const response = await updateUser(user.value)
    if (response === undefined) {
      uni.showToast({
        title: '更新成功',
        icon: 'success'
      })
      await fetchUserInfo()
    } else {
      uni.showToast({
        title: '更新失败',
        icon: 'error'
      })
    }
  } catch (error) {
    console.error('更新用户信息失败', error)
  }
}
</script>


<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f5f5;
}

.header {
  width: 100%;
  height: 200px;
  background-color: #3b82f6;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  margin-bottom: 20px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 10px;
}

.choose-image-btn {
  background-color: #fff;
  color: #3b82f6;
  padding: 10px;
  border-radius: 5px;
  margin-bottom: 20px;
}

.form {
  width: 100%;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  width: 80px;
}

.input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.save-btn {
  width: 100%;
  padding: 10px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  text-align: center;
}
</style>
